﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;
    using TVN.ShopMan.ApplicationInterface.Helpers;

    public partial class GenericDataFormEdit : Form
    {
        private static readonly ILogger logger = Program.Logger.CreateChildLogger("GenericDataFormEdit");
        private IRepository<Repository> repositoryRepository = null;
        private Repository selectedRepository = null;

        public GenericDataFormEdit()
        {
            InitializeComponent();

            this.repositoryRepository = Program.Container.Resolve<IRepository<Repository>>();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            bool isCreating = ((this.selectedRepository == null) || (this.selectedRepository.Id <= 0));
            if (AppHelper<Unit>.IsExists(Unit.Properties.Name, this.txtUnitName.Name, isCreating))
            {
                this.txtUnitName.Focus();
            }
            else
            {
                if (this.SaveUnit())
                {
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    // TODO: Raises error
                }
            }
        }

        private bool SaveUnit()
        {
            bool result = false;

            try
            {
                if (this.selectedRepository == null)
                {
                    this.selectedRepository = new Repository
                    {
                        CreatedDate = DateTime.Now,
                        Creator = Program.SessionData.ActiveAccount,
                    };
                }
                else
                {
                    this.selectedRepository.LastModifiedDate = DateTime.Now;
                    this.selectedRepository.LastModifier = Program.SessionData.ActiveAccount;
                }

                this.selectedRepository.Name = this.txtUnitName.Text;

                if (this.selectedRepository.Id > 0)
                {
                    this.repositoryRepository.Update(this.selectedRepository);
                }
                else
                {
                    this.repositoryRepository.Insert(this.selectedRepository);
                }

                result = true;
            }
            catch (Exception ex)
            {
                logger.Error("Could not save unit", ex);
                result = false;
            }

            return result;
        }
    }
}
